package net.guruqu.cds;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Vector;

public abstract class Node {
	private int UID;
	private Vector<Integer> neighbour;

	private HashMap<Integer, LinkedList<Object>> messageToNeighbour;

	private HashMap<Integer, LinkedList<Object>> incomingMessage;

	private Network network;
	
	private String text="";

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Node() {
		neighbour = new Vector<Integer>();
		messageToNeighbour = new HashMap<Integer, LinkedList<Object>>();
		incomingMessage = new HashMap<Integer, LinkedList<Object>>();
	}

	public void broadCastMessage(Object message) {
		for (Integer i : neighbour) {
			sendMessage(i, message);
		}
	}

	public void floodMessage(Object message) {
		for (Node i : network.getNodes()) {
			if (i != this)
				sendMessage(i.getUID(), message);
		}
	}

	public void clearIncomingMessage() {
		incomingMessage.clear();
	}

	protected Node sendMessage(Integer neighbour, Object message) {
		LinkedList<Object> list = messageToNeighbour.get(neighbour);
		if (list == null) {
			list = new LinkedList<Object>();
			messageToNeighbour.put(neighbour, list);
		}
		list.add(message);
		return this;
	}

	public abstract void executeNode();

	public int getUID() {
		return UID;
	}

	public void setUID(int uid) {
		UID = uid;
	}

	public Network getNetwork() {
		return network;
	}

	public void setNetwork(Network network) {
		this.network = network;
	}

	public Vector<Integer> getNeighbour() {
		return neighbour;
	}

	public HashMap<Integer, LinkedList<Object>> getMessageToNeighbour() {
		return messageToNeighbour;
	}

	public HashMap<Integer, LinkedList<Object>> getIncomingMessage() {
		return incomingMessage;
	}

	public void addMessage(Integer from, Object message) {
		LinkedList<Object> list = incomingMessage.get(from);
		if (list == null) {
			list = new LinkedList<Object>();
			incomingMessage.put(from, list);
		}
		list.add(message);
	}
}
